package jh.com.jhappbf.httputils;

import android.app.Activity;
import android.os.Environment;
import android.widget.Toast;

import com.ab.fragment.AbLoadDialogFragment;
import com.ab.util.AbDialogUtil;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import jh.com.jhappbf.R;
import jh.com.jhappbf.ui.State;

/**
 * @author Administrator
 */
public class ExportHelper {
    private AbLoadDialogFragment mDialogFragment;
    private Activity mContext;
    private String mType;
    private String mUrl;

    public ExportHelper(AbLoadDialogFragment dlg, String url, Activity context, String type) {
        mDialogFragment = dlg;
        mUrl = url;
        mContext = context;
        mType = type;
    }

    public void export() {
        mDialogFragment = AbDialogUtil.showLoadDialog(mContext,
                R.mipmap.ic_load, "正在导入Excel,请稍等...");
        mDialogFragment.setCancelable(false);
        mDialogFragment.setAbDialogOnLoadListener(() -> exportExcel(mUrl));
    }

    /**
     * 导出 Excel
     */
    private void exportExcel(final String url) {
        OkHttpClient okhttp = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = okhttp.newCall(request);
        call.enqueue(new Callback() {

            @Override
            public void onResponse(Response response) throws IOException {
                InputStream stream;
                int len;
                byte[] buff = new byte[2048];
                stream = response.body().byteStream();
                String path = dirIsExist("jinheng");

                File file = new File(path, State.mAccount + mType + "报表." + getExtNameFromUrl(url));

                FileOutputStream fos = new FileOutputStream(file);
                try {
                    while ((len = stream.read(buff)) != -1) {
                        fos.write(buff, 0, len);
                    }
                    fos.flush();//java在使用流时,都会有一个缓冲区,按一种它认为比较高效的方法来发数据:把要发
                    // 的数据先放到缓冲区,缓冲区放满以后再一次性发过去,而不是分开一次一次地发.
                    //而flush()表示强制将缓冲区中的数据发送出去,不必等到缓冲区满.
                    //所以如果在用流的时候,没有用flush()这个方法,很多情况下会出现流的另一边读不到数据的问题,特别是在数据特别小的情况下.
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    stream.close();
                    fos.close();
                }


                mContext.runOnUiThread(() -> {
                    if (mDialogFragment != null) {
                        mDialogFragment.dismiss();
                    }
                    Toast.makeText(mContext, "导出成功[本地存储 jinheng文件夹下]", Toast.LENGTH_LONG).show();
                });
            }

            @Override
            public void onFailure(Request arg0, IOException arg1) {
                mContext.runOnUiThread(() -> {
                    if (mDialogFragment != null) {
                        mDialogFragment.dismiss();
                    }
                    Toast.makeText(mContext, "导出错误!", Toast.LENGTH_LONG).show();
                });
            }
        });
    }


    /**
     * @param url
     * @return 从下载连接中解析出文件名
     */
    private String getNameFromUrl(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }

    private String getExtNameFromUrl(String url) {
        return url.substring(url.lastIndexOf(".") + 1);
    }


    private String dirIsExist(String saveDir) throws IOException {
        File downLoad = new File(Environment.getExternalStorageDirectory(), saveDir);
        if (!downLoad.mkdir()) {
            downLoad.createNewFile();
        }
        String path = downLoad.getAbsolutePath();
        return path;

    }
}